import base from './base';
import { getAntd, getLabel, getEcCom } from './convert';
import { doSubmitForm } from './submit';
import { reloadRequestPage } from './formUtil';
import * as API_REQ from '../apis/req';

//获取连续处理相关参数
export const getContinuationProcessParams = () => {
    let continuationProcessParams = {};
    //获取查询参数
    if(window.opener && window.opener.continuationProcessQueryParams) {
        continuationProcessParams = {...continuationProcessParams, ...window.opener.continuationProcessQueryParams};
    }
    //获取table排序参数
    if(window.opener && window.opener.WorkflowListDoingUtil && window.opener.WorkflowListDoingUtil.getTableSortParams) {
        let newContinuationProcessSortParams = [];
        let continuationProcessSortParams = window.opener.WorkflowListDoingUtil.getTableSortParams();
        if(continuationProcessSortParams && continuationProcessSortParams.length > 0) {
            
            //IE下这个对象里有奇怪的东西，item遍历取出来放到一个新的对象里，不然下面SON.stringify会有问题
            continuationProcessSortParams.map(item => {
                newContinuationProcessSortParams.push(item);
            })
            continuationProcessParams['tableSortParams'] = JSON.stringify(newContinuationProcessSortParams);
        }
    }

    Object.keys(continuationProcessParams).map( key => {
        if(continuationProcessParams[key] == undefined || continuationProcessParams[key] == null) {
            delete  continuationProcessParams[key];
        }
    })

    return continuationProcessParams;
}

//显示连续处理自动切换的提示
export const showConProcessSwitchTip = (queryParams) => {
    const { message } = getAntd();
    if(queryParams.showConProcessSwitchTip == '1') {
        
        message.success(getLabel(528806, '流程已处理，自动为您打开下一条'), 3);

        //去除连续处理提示的参数，防止刷新表单时弹出提示
        const newHref = window.location.href.replace("&showConProcessSwitchTip=1", '');
        window.history.pushState({}, 0, newHref);
    }
}

// 连续处理切换流程
export const switchRequest = (type, showConProcessSwitchTip) => {
    const { continuationProcessInfo } = base.globalStore;
    const { currentIndex, requestId } = continuationProcessInfo;

    let switchToRequestId = '';

    //获取跳转的下一requestid
    let continuationProcessParams = getContinuationProcessParams();
    API_REQ.getContinnuationProcessInfo({
        viewScope: "doing",
        switchType : type,
        currentIndex : currentIndex,
        currentRequestId : requestId,
        ...continuationProcessParams
    }).then(data => {
        if (data.switchRequestId > 0) {
            switchToRequestId = data.switchRequestId;
            reloadRequestPage({requestid: switchToRequestId, isOpenContinuationProcess  : '1', f_weaver_belongto_userid : data.userId,f_weaver_belongto_usertype : data.userType, showConProcessSwitchTip : (showConProcessSwitchTip ? '1' : '0') });
        } else  {
            try {
                window.top.close();
            } catch (e) {
                window.close();
            }
        }
    })
  };

